<script setup>
import { ref, computed, watchEffect, watch, toValue, onMounted, onBeforeUnmount } from 'vue'
// import { register } from '@tauri-apps/plugin-global-shortcut';
import { useAutoAnimate } from '@formkit/auto-animate/vue'
import { useFetch } from './fetch.js'
import dayjs from 'dayjs';
import {
  TransitionRoot,
  TransitionChild,
  Dialog,
  DialogPanel,
  DialogTitle,
} from '@headlessui/vue'

const [parent] = useAutoAnimate();

const searchDoc = ref('');
const modalData = ref({});
const docList = ref([]);
const errorRequest = ref(null);

const isOpen = ref(false);
const docFilter = computed(() => docList?.value?.graph_list?.filter((doctor) => (doctor?.fam.toUpperCase()).includes(searchDoc?.value.toUpperCase())))


async function setModalData(newData) {
  modalData.value = newData;
  isOpen.value = true;
}

watch(() => docFilter.value, () => {
  if (docFilter.value.length === 1) {
    modalData.value = docFilter.value[0]
    isOpen.value = true
  }
})

async function fetchData() {
  fetch(toValue(`http://192.168.100.48:8000/api/lab/rasp_all/`), {
    mode: "cors",
  }).then((res) => res.json()).then((json) => (docList.value = json)).catch((err) => (errorRequest.value = err))
  // .then((response) => response.json()).then((json) => (docList.value = json)).catch((error) => (errorRequest.value = error))
}

onMounted(() => {
  fetchData()
})

const updater = setInterval(() => fetchData(), 1000 * 60 * 2)

onBeforeUnmount(() => {
  clearInterval(updater.value)
})

function closeModal() {
  isOpen.value = false
  searchDoc.value = ''
}
function openModal() {
  isOpen.value = true
}

</script>

<template>
  <div v-if="errorRequest">{{ errorRequest }}</div>
  <div class="relative">
    <div ref="parent" class="py-10">
      <input v-model="searchDoc"
        class=" fixed top-1 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
        placeholder="Введите фамилию врача..." />
      <div v-for="value in  docFilter " :key="value.doc" @click="setModalData(value)">
        <div class="flex flex-row flex-nowrap gap-4 text-left text-lg p-1 border border-1 border-slate-400"
          :class="[value.is_unwork ? 'bg-red-400' : value.is_unwork_soon ? 'bg-yellow-400' : '']">
          <div class="basis-4/12 self-center ">{{ value.fam }} {{ value.im }} {{ value.ot }}
          </div>
          <div class="basis-3/12 self-center ">{{ value.nspz }}</div>
          <div class="basis-2/12 self-center text-center ">{{ value.is_unwork ?
    value.rsn_unwork : "Работает"
            }}</div>
          <div class="basis-3/12 self-center text-center ">{{ value.nslp }}</div>
        </div>
      </div>
    </div>
  </div>

  <TransitionRoot appear :show="isOpen" as="template">
    <Dialog as="div" @close="closeModal" class="relative z-10">
      <TransitionChild as="template" enter="duration-300 ease-out" enter-from="opacity-0" enter-to="opacity-100"
        leave="duration-200 ease-in" leave-from="opacity-100" leave-to="opacity-0">
        <div class="fixed inset-0 bg-black/25" />
      </TransitionChild>

      <div class="fixed inset-0 overflow-y-auto">
        <div class="flex min-h-full items-center justify-center p-4 text-center">
          <TransitionChild as="template" enter="duration-300 ease-out" enter-from="opacity-0 scale-95"
            enter-to="opacity-100 scale-100" leave="duration-200 ease-in" leave-from="opacity-100 scale-100"
            leave-to="opacity-0 scale-95">
            <DialogPanel
              class="w-full transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all max-w-4xl">
              <DialogTitle as="h3" class="text-lg font-medium leading-6 text-gray-900">
                <div>{{ modalData.fam }} {{ modalData.im }} {{ modalData.ot }}</div>
              </DialogTitle>
              <div class="mt-2">
                <div>{{ modalData.nspz }}</div>
                <div>{{ modalData.nslp }}</div>
                <div class="" :class="[new Date().getDate() % 2 === 0 ? 'bg-green-400' : '']">Четные дни {{
    modalData.even_day }}
                </div>
                <div class="" :class="[new Date().getDate() % 2 !== 0 ? 'bg-green-400' : '']">Нечетные дни {{
    modalData.noeven_day }}
                </div>
                <div v-if="modalData.is_unwork" class="flex flex-row">
                  <div class="text-red-500">Не работает: {{ modalData.rsn_unwork }}</div>

                  <div class="px-1 text-red-500">{{ modalData.date2_unwork && modalData.date2_unwork !==
    modalData.date1_unwork ?
    `с ${dayjs(modalData.date1_unwork).format('DD.MM.YYYY')} по
                    ${dayjs(modalData.date2_unwork).format('DD.MM.YYYY')}` :
    dayjs(modalData.date1_unwork).format('DD.MM.YYYY') }}</div>
                </div>
                <div v-else class="text-green-500">
                  Сегодня работает
                </div>
                <div v-for=" period  in  modalData.unwork " :key="period.iblc">
                  <div v-if="period.cast != modalData.date1_unwork || period.cast1 != modalData.date2_unwork"
                    class="text-red-500">Следующий нерабочий период: {{
    period.nrsn_ }} с {{
    dayjs(period.cast).format('DD.MM.YYYY') }} по {{
    dayjs(period.cast1).format('DD.MM.YYYY') }}</div>
                </div>
                <div class="flex flex-row">
                  <div v-if="modalData.is_unwork">
                    <VCalendar :attributes="[{
    highlight: 'red',
    dates: [[new Date(modalData.date1_unwork), new Date(modalData.date2_unwork)]]
  }]
    " borderless :disable-page-swipe="true" />
                  </div>
                  <div v-if="new Date(modalData.date2_unwork).getMonth() > new Date(modalData.date1_unwork).getMonth()">
                    <VCalendar :attributes="[{
    highlight: 'red',
    dates: [[new Date(modalData.date1_unwork), new Date(modalData.date2_unwork)]]
  }]" borderless :initial-page="{ month: new Date(modalData.date2_unwork).getMonth() + 1, year: new Date(modalData.date2_unwork).getFullYear() }" />
                  </div>
                </div>
                <div class="mt-4">
                  <button type="button"
                    class="inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
                    @click="closeModal">
                    Закрыть
                  </button>
                </div>
              </div>
            </DialogPanel>
          </TransitionChild>
        </div>
      </div>
    </Dialog>
  </TransitionRoot>
</template>

<style scoped></style>
